package com.poizon.infrastructure.starter.redis;

import cn.hutool.core.util.StrUtil;
import cn.hutool.extra.spring.SpringUtil;
import com.poizon.infrastructure.cache.core.repo.ICacheDbRepo;
import com.poizon.infrastructure.cache.core.util.IRedisUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.data.redis.core.StringRedisTemplate;

import java.util.Map;
import java.util.Optional;

import static com.poizon.infrastructure.cache.core.domain.value.constants.CacheConstants.stringRedisTemplateBeanName;

@Slf4j
public class RedisAutoConfig {
    /**
     * 注入缓存DB仓储实现
     */
    @Bean("reidsCacheDbRepo")
    public ICacheDbRepo iCacheDbRepo(IRedisUtil iRedisUtil) {
        log.info(">初始化缓存DB仓储实现未Redis");
        return new RedisCacheDbRepo(iRedisUtil);
    }
    /**
     * 注入Redis工具类
     */
    @Bean
    public IRedisUtil iRedisUtil() {
        log.info(">初始化Redis工具类");
        Map<String, StringRedisTemplate> beansOfType = SpringUtil.getBeansOfType(StringRedisTemplate.class);
        if (beansOfType == null || beansOfType.values().size() == 0) {
            log.error(StrUtil.format(">不存在stringnRedisTemplate的实现"));
        }
        StringRedisTemplate stringRedisTemplate = beansOfType.get(stringRedisTemplateBeanName);
        if (stringRedisTemplate == null) {
            log.error(StrUtil.format(">不存在指定的stringRedisTemplate的实现"));
        }
        stringRedisTemplate = Optional.ofNullable(stringRedisTemplate).orElse(beansOfType.values().iterator().next());
        return new RedisUtil(stringRedisTemplate);
    }


}
